#include "server.h"
#include "tcl_interp.h"
#include <sys/socket.h>
#include <iostream>
using namespace std;

void cmdq::push (int conn, const string& cmd) {
  while (state == busy) usleep (1);
  state = busy;
    q.push (qdata (conn, cmd));
    //cout << "pushed: " << cmd;
  state = free;
}

void cmdq::pop () {
  while (state == busy) usleep (1);
  state = busy;
  if (!q.empty ()) {
    qdata& qd = q.front ();
    if (qd.cmd != "") {
      extern tcl_interp interpreter;
      interpreter (qd.cmd);
      /*cout << "ran: " << qd.cmd;
      if (interpreter.result != "") cout << "result = " << interpreter.result << endl;*/
      if (qd.connection != -1) {
        if (interpreter.result.length ()) 
          send_all (qd.connection, interpreter.result.c_str());
      }
    }
    q.pop ();
  }
  state = free;
}

void send_all (int connection, const string& str) {
  const char* p = str.c_str ();
  int sent = 0, length = str.length ();
  while (length > 0) {
    sent = write (connection, p, length);
    if (sent == -1) break;
    length -= sent;
    p += sent;
  }
}
